package main

import (
	"fmt"
	"net"
	"os"
	"syscall"
)

const (
	// 与receiver监听的unixsocks文件地址一致
	socksPath  = "./unix_sock"
)

func main() {
	file, err := os.Open("./tmp.txt")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	fdnum := file.Fd()
	fmt.Printf("%b %b %b %b\n", byte(fdnum), byte(fdnum >> 8), byte(fdnum >> 16), byte(fdnum >> 24))
	fmt.Printf("ready to send fd: %d\n", fdnum)
	//UnixRights将一组打开的文件描述符编码为套接字控制消息，以便发送到另一个进程。
	data := syscall.UnixRights(int(fdnum))
	fmt.Println(111, data)
	raddr, err := net.ResolveUnixAddr("unix", socksPath)
	if err != nil{
		panic(err)
	}
	// 连接UnixSock
	conn, err := net.DialUnix("unix", nil, raddr)
	if err != nil{
		panic(err)
	}
	// 发送msg
	n, oobn, err := conn.WriteMsgUnix([]byte("boy"), data, nil)
	if err != nil{
		panic(err)
	}
	fmt.Printf("WriteMsgUnix = %d, %d, %d\n", n, oobn, len(data))
	fmt.Printf("write %d data success\n", n)
}
